<template>
  <div>
    <Menu />
    <layout>
      <template v-slot:main>
        <el-row :gutter="20">
          <!-- left -->
          <el-col :lg="18" class="el_margin" :md="16">
            <!-- 新闻头条 -->
            <div class="new_container height_light_bgcolor">
              <div class="title font_color_common" style="margin-bottom:20px">
                <el-icon style="font-size:24px">
                  <Tickets color="#409eff" />
                </el-icon>
                <h3 class="title_sm">{{ $t('indexTitle.new') }}</h3>
              </div>
              <div class="swiper_content_wrapper font_size_common">
                <el-row :gutter="30">
                  <el-col :lg="14">
                    <div class="swiper_container" v-loading="swiperLoading" element-loading-text="正在玩命加载中...">
                      <swiper @swiper="onSwiper" :autoplay="{ delay: 2500, disableOnInteraction: true }" :loop="true"
                        :modules="modules" @mouseenter="enter" @mouseleave="leave" :pagination="{ clickable: true }"
                        :navigation="true" class="my_swiper">
                        <swiper-slide v-for="item in bannerData" :key="item.id" @click="handleClickSwiperSlide(item)">
                          <div style="height:80%" class="cursor_class">
                            <img :src="proxy.$baseImgUrl + item.imgUrl" :alt="item.title">
                          </div>
                          <div class="swiper_title text_ellipsis text_decoration cursor_class">
                            {{ item.title }}
                          </div>
                        </swiper-slide>
                      </swiper>
                    </div>
                  </el-col>
                  <el-col :lg="10">
                    <div class="new_wrapper" v-loading="homeBlogLoading" element-loading-text="正在玩命加载中...">
                      <div class="new_item cursor_class" v-for="item in homeBlogData.data.value" @click="() => {
                        router.push({
                          name: 'article-detail',
                          params: {
                            id: item.id
                          }
                        })
                      }">
                        <p class="new_item_title text_decoration text_ellipsis">{{ item.title }}</p>
                        <span class="new_item_desc text_ellipsis2 font_color_common">{{ item.description }}</span>
                      </div>
                      <!-- homeBlogData.total.value -->
                      <!-- v-if="data.total > 0" -->
                      <div class="pagination_container">
                        <el-pagination background layout="prev,next" :total="homeBlogData.total.value"
                          v-if="homeBlogData.total.value > 0" v-model:page-size="homeBlogSearchParams.pageSize"
                          v-model:current-page="homeBlogSearchParams.pageNum" @current-change="handleCurrentChange" />
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
            <!-- 博客精选 -->
            <div class="blog_hot_container height_light_bgcolor">
              <div class="title font_color_common" style="margin-bottom:20px">
                <el-icon style="font-size:24px">
                  <Document color="#409eff" />
                </el-icon>
                <h3 class="title_sm">{{ $t('indexTitle.blogArticle') }}</h3>
              </div>
              <div class="tab_wrapper">
                <el-tabs v-model="activeName" @tab-click="handleClick">
                  <el-tab-pane :label="items.label" :name="items.name" v-for="items in tabPanel" :key="items.id">
                    <div class="tab_pane_wrapper" :style="{ padding: notelistLoading ? '45px 0' : '' }">
                      <div v-loading="notelistLoading" element-loading-text="正在玩命加载中...">
                        <Article v-for="item in notelistData" @liked="handleClickArticleLiked($event, items.name)"
                          :key="item.id" :id="item.id" :coverPicture="item.coverPicture" :title="item.title"
                          :description="item.description" :groups="item.groups" :likeNum="item.likeNum"
                          :nickName="item.user.nickName" :commentCount="item.commentCount"
                          :pageViewNum="item.pageViewNum" :createTime="item.createTime" :isLike="item.isLike"
                          :directionId="item.directionId" />
                      </div>
                      <div class="look_more_btn" v-show="!notelistLoading">
                        <el-button type="primary" style="margin-top:50px"
                          @click="() => { router.push({ path: '/blog' }) }">{{ $t('indexTitle.lookMore') }}
                        </el-button>
                      </div>
                    </div>
                  </el-tab-pane>
                </el-tabs>
                <div class="pos_btn_more">
                  <el-button type="primary" :icon="More" link @click="() => { router.push({ path: '/blog' }) }">
                    {{ $t('indexTitle.more') }}
                  </el-button>
                </div>
              </div>
            </div>
          </el-col>
          <!-- right -->
          <el-col :lg="6" class="el_margin" :md="8">
            <div class="recommend_container height_light_bgcolor">
              <div class="recommend_title_wrapper">
                <div class="title font_color_common">
                  <el-icon style="font-size:24px">
                    <UserFilled color="#409eff" />
                  </el-icon>
                  <h3 class="title_sm">{{ $t('indexTitle.recommendUserTitle') }}</h3>
                </div>
                <div class="recommedn_refesh cursor_class" @click="changeCircle" style="user-select:none">
                  <el-icon>
                    <RefreshLeft />
                  </el-icon>
                  <span>{{ $t('indexTitle.batch') }}</span>
                </div>
              </div>
              <div class="recommend_content_wrapper">
                <el-row v-loading="recommendUserListLoading" element-loading-text="正在玩命加载中...">
                  <el-col :lg="24" v-for="(item, index) in recomdUserParmas.newList.value" :key="index">
                    <div class="blog_user_item">
                      <div class="avatar_and_info ">
                        <Avatar :avatar-img-url="item.avatar" :nick-name="item.nickName" :remark="item.remark"
                          :interestValue="item.interestValue" :userId="item.userId" :noteNum="item.noteNum" :likeNum="item.likeNum" :followNum="item.followNum"/>
                        <div class="recommend_user_info text_ellipsis">
                          <p class="text_ellipsis cursor_class" @click="handleClickToUserBlog(item.userId)">{{
                              item.nickName
                          }}</p>
                          <span class="text_muted text_ellipsis">{{ item.remark }}</span>
                        </div>
                      </div>
                      <div style="margin-left:10px">
                        <template v-if="item.followType !== 3">
                          <el-button type="primary" round :loading="foucsBtnLoading"
                            @click="handleClcikFollow(0, item.userId)" v-if="item.followType === 1">{{
                                $t('focus')
                            }}</el-button>
                          <el-button round v-else-if="item.followType === 0" :loading="foucsBtnLoading"
                            @click="handleClcikFollow(1, item.userId)">已关注</el-button>
                          <el-button round v-else-if="item.followType === 2" :loading="foucsBtnLoading"
                            @click="handleClcikFollow(1, item.userId)">互相关注</el-button>
                        </template>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
            <div class="friend_link_container height_light_bgcolor">
              <div class="title font_color_common" style="margin-bottom:20px">
                <el-icon style="font-size:24px">
                  <OfficeBuilding color="#409eff" />
                </el-icon>
                <h3 class="title_sm">{{ $t('indexTitle.officalUserTitle') }}</h3>
              </div>
              <div v-loading="adminUserLoading" element-loading-text="正在玩命加载中...">
                <div class="blog_user_item">
                  <div class="avatar_and_info ">
                    <Avatar :avatar-img-url="adminUserList.data.avatar" :nick-name="adminUserList.data.nickName"
                      :remark="adminUserList.data.remark" :interestValue="adminUserList.data.interestValue"
                      :userId="adminUserList.data.userId" :noteNum="adminUserList.data.noteNum" :likeNum="adminUserList.data.likeNum" :followNum="adminUserList.data.followNum"/>
                    <div class="recommend_user_info text_ellipsis">
                      <p class="text_ellipsis cursor_class" @click="handleClickToUserBlog(adminUserList.data.userId)">{{
                          adminUserList.data.nickName
                      }}
                      </p>
                      <span class="text_muted text_ellipsis">{{ adminUserList.data.remark }}</span>
                    </div>
                  </div>
                  <div style="margin-left:10px">
                    <template v-if="adminUserList.data.followType !== 3">
                      <el-button type="primary" round :loading="foucsBtnLoading"
                        @click="handleClcikFollow(0, adminUserList.data.userId)" v-if="adminUserList.data.followType === 1">{{
                            $t('focus')
                        }}</el-button>
                      <el-button round v-else-if="adminUserList.data.followType === 0" :loading="foucsBtnLoading"
                        @click="handleClcikFollow(1, adminUserList.data.userId)">已关注</el-button>
                      <el-button round v-else-if="adminUserList.data.followType === 2" :loading="foucsBtnLoading"
                        @click="handleClcikFollow(1, adminUserList.data.userId)">互相关注</el-button>
                    </template>
                  </div>
                </div>
              </div>
            </div>
            <div class="friend_link_container height_light_bgcolor">
              <div class="title font_color_common" style="margin-bottom:20px">
                <el-icon style="font-size:24px">
                  <Link color="#409eff" />
                </el-icon>
                <h3 class="title_sm">{{ $t('indexTitle.likeLinkTitle') }}</h3>
              </div>
              <div>
                <a href="https://www.zhipin.com/" target="_blank">
                  <el-button class="link_item">BOSS直聘</el-button>
                </a>
                <a href="https://www.vcg.com/" target="_blank">
                  <el-button class="link_item">视觉中国</el-button>
                </a>
                <a href="https://www.iviewui.com/docs/introduce" target="_blank">
                  <el-button class="link_item">View UI</el-button>
                </a>
                <a href="https://www.uisdc.com/" target="_blank">
                  <el-button class="link_item">优设网</el-button>
                </a>
                <a href="https://www.devpress.cn/" target="_blank">
                  <el-button class="link_item">DevPress社区</el-button>
                </a>
                <a href="https://www.kanzhun.com/" target="_blank">
                  <el-button class="link_item">看准网</el-button>
                </a>
                <a href="https://www.veer.com/" target="_blank">
                  <el-button class="link_item">Veer</el-button>
                </a>
              </div>
            </div>
            <div class="about_container height_light_bgcolor">
              <div class="title font_color_common" style="margin-bottom:20px">
                <el-icon style="font-size:24px">
                  <Location color="#409eff" />
                </el-icon>
                <h3 class="title_sm">{{ $t('indexTitle.aboutusTitle') }}</h3>
              </div>
              <div class="about_us_content">
                <el-avatar :size="50" :src="duck" />
                <p>致力于收集开发者遇到的问题，把你的所遇到的问题记录在此吧！<span class="primay">站长鸭博士。</span></p>
              </div>
            </div>
          </el-col>
        </el-row>
      </template>
    </layout>
    <Footer />
  </div>
</template>

<script lang="ts" setup>
import Menu from '@/components/Menu/index.vue'
import Layout from '@/components/Layout/index.vue'
import Footer from '@/components/Footer/index.vue'
import Avatar from '@/components/Avatar/index.vue'
import Article from '@/components/Article/index.vue'
import duck from '@/assets/images/duck.png'
import {
  Tickets,
  UserFilled,
  RefreshLeft,
  Plus,
  Document,
  User,
  ChatDotSquare,
  View,
  Timer,
  Pointer,
  More,
  Location,
  Link,
  OfficeBuilding
} from '@element-plus/icons-vue'
import { getBanner, getBlogList, recommendUser, adminUser } from '@/api/index'
import { Swiper, SwiperSlide } from 'swiper/vue'
import { Pagination, Navigation } from 'swiper'
import 'swiper/css'
import 'swiper/css/navigation'
import 'swiper/css/pagination'
import { Autoplay } from 'swiper'
import { onMounted, ref, getCurrentInstance, toRaw, reactive, toRefs } from 'vue'
import { ElMessage, TabsPaneContext } from 'element-plus'
import i18n from '@/i18n/index'
import router from '@/router'
import { followUser } from '@/api/user'
// 分页参数约束接口
interface Page {
  pageNum: number,
  pageSize: number,
}
const { proxy } = getCurrentInstance()
const modules = [Autoplay, Pagination, Navigation]
const tabPanel = ref([{
  id: 1,
  name: 'first',
  label: '推荐'
  // label: i18n.global.t('indexTitle.articleTitle1')
}, {
  id: 2,
  name: 'second',
  label: '最新'
  // label: i18n.global.t('indexTitle.articleTitle2')
}, {
  id: 3,
  name: 'third',
  label: '热门'
  // label: i18n.global.t('indexTitle.articleTitle3')
}])
//定义swiperNew,目的获取非响应式swiper
let swiperNew: any
const swiperLoading = ref(false)
const bannerData = ref<Array<any>>([])
const homeBlogLoading = ref<boolean>(false)
const homeBlogSearchParams = reactive<any>({
  pageNum: 1,
  pageSize: 3,
  isHome: 1
})
const homeBlogData = toRefs(reactive<any>({
  data: [],
  total: 0
}))
const activeName = ref('first')
// 推荐加载loading
const notelistLoading = ref(false)
// 推荐列表文章数据
const notelistData = ref<any[]>([])
// 推荐博客文章分页参数
const notelistPageQuery: Page = reactive({
  pageNum: 1,
  pageSize: 10,
})
// 推荐博主loding
const recommendUserListLoading = ref(false)
// 官方博客
const adminUserList = reactive<any>({ data: {} })
// 官方博客loading
const adminUserLoading = ref(false)
const recomdUserParmas = toRefs(reactive<any>({
  qList: [],
  //处理后的list
  newList: [],
  //截取第几组的开始参数
  timeStart: 0,
  //截取第几组的结束参数
  timeEnd: 1,
  //默认为0组
  group: 0,
  //一页展示list数量
  num: 4,
  //点击的次数
  clickNum: 0,
}))
const foucsBtnLoading = ref<boolean>(false)
const handleClcikFollow = async (status: number, followedUserId: number) => {
  try {
    const res: any = await followUser({
      status,
      followedUserId
    })
    if (res) {
      if (status === 1) {
        ElMessage({
          message: '取关成功',
          type: 'success',
          duration: 2 * 1000
        })
      } else {
        ElMessage({
          message: '关注成功',
          type: 'success',
          duration: 2 * 1000
        })
      }
      getRecommendUser()
      getAdminUser()
    }
  } finally {

  }
}
/**
 * 获取博客文章列表
 */
const getBlogListData = async (cate?: any) => {
  try {
    notelistLoading.value = true
    const res: any = await getBlogList({ ...cate, ...notelistPageQuery })
    notelistData.value = res.rows
  } finally {
    notelistLoading.value = false
  }
}
/**
 * 获取推荐博主
 */
const getRecommendUser = async () => {
  try {
    recommendUserListLoading.value = true
    const { data }: any = await recommendUser()
    recomdUserParmas.qList.value = data
    renderR()
  } finally {
    recommendUserListLoading.value = false
  }
}
/**
 * 获取官方博客
 */
const getAdminUser = async () => {
  try {
    adminUserLoading.value = true
    const { data } = await adminUser({ userId: 1 })
    adminUserList.data = data
    console.log(adminUserList);
  } finally {
    adminUserLoading.value = false
  }
}
/**
 * 获取轮播图
 */
const getBannerData = async () => {
  try {
    swiperLoading.value = true
    const { data } = await getBanner()
    bannerData.value = data
  } finally {
    swiperLoading.value = false
  }
}
//鼠标移入
const enter = () => {
  swiperNew.autoplay.stop()
}
//鼠标移出
const leave = () => {
  swiperNew.autoplay.start()
}
const onSwiper = (swiper: any) => {
  swiperNew = toRaw(swiper) //拿到swiper对象再转换为非响应式
}
const handleClickSwiperSlide = (item: any) => {
  console.log(item)
  if (item.isOutside === 1) {
    window.open(item.outsideHref)
  } else {
    const url = router.resolve({
      name: 'article-detail',
      params: {
        id: item.noteId
      }
    })
    window.open(url.href, '_blank')
  }
}
/**
 * tab点击
 */
const handleClick = (tab: TabsPaneContext, event: Event) => {
  // 断言是string类型
  activeName.value = tab.props.name as string
  console.log(activeName.value);
  if (activeName.value === 'first') {
    getBlogListData({ isOfficialRecommend: 1 })
  } else if (activeName.value === 'second') {
    getBlogListData()
  } else if (activeName.value === 'third') {
    getBlogListData({ isHot: 1 })
  }
}
// 监听点赞，更新数据
const handleClickArticleLiked = (e: any, name: string) => {
  console.log(name);
  if (name === 'first') {
    getBlogListData({ isOfficialRecommend: 1 })
  } else if (name === 'second') {
    getBlogListData()
  } else if (name === 'third') {
    getBlogListData({ isHot: 1 })
  }
}
/**
 * 请求轮播图旁边的博客数据
 */
const getHomeBlogData = async () => {
  try {
    homeBlogLoading.value = true
    const { rows, total }: any = await getBlogList(homeBlogSearchParams)
    homeBlogData.data.value = rows
    homeBlogData.total.value = total
    console.log(homeBlogData.data);

  } finally {
    homeBlogLoading.value = false
  }

}

const handleCurrentChange = (val: number) => {
  homeBlogSearchParams.pageNum = val
  getHomeBlogData()
}
// -----------------------------------换一换------------------------
//每点击一次，记录次数
function autoIncre() {
  recomdUserParmas.clickNum.value++;
  recomdUserParmas.timeStart.value++;
  recomdUserParmas.timeEnd.value++;
}
//计算将点击次数和开始截取的参数清空, 如果点击此时大于当前数据的组数，则重新开始计数。
function clear() {
  if (recomdUserParmas.clickNum.value > recomdUserParmas.group.value - 1) {
    recomdUserParmas.timeStart.value = 0;
    recomdUserParmas.timeEnd.value = 1;
    recomdUserParmas.clickNum.value = 0;
  }
}
// 计算数据的长度，共分为几组，如果不能整除则加1
function listlen() {
  var len = recomdUserParmas.qList.value.length;
  recomdUserParmas.group.value = len / recomdUserParmas.num.value;
  if (len % recomdUserParmas.num.value != 0) {
    recomdUserParmas.group.value = parseInt(recomdUserParmas.group.value) + 1;
  }
}
//截取当前每组的数据
function renderR() {
  // recommendUserListLoading.value = true
  recomdUserParmas.newList.value = recomdUserParmas.qList.value.slice(
    recomdUserParmas.num.value * recomdUserParmas.timeStart.value,
    recomdUserParmas.num.value * recomdUserParmas.timeEnd.value
  );
  // recommendUserListLoading.value = false
  console.log(recomdUserParmas.newList.value);

}
// 换一批
function changeCircle() {
  if (recomdUserParmas.qList.value.length > 4 && recomdUserParmas.qList.value.length > recomdUserParmas.num.value) {
    //点击的时候获取分为几组
    listlen();
    //每点击一次记录点击次数
    autoIncre();
    clear();
    renderR();
  }
}
// -----------------------------------换一换------------------------
const handleClickToUserBlog = (userId: number | string) => {
  router.push({
    name: 'user-blog',
    params: {
      id: userId
    }
  })
}
onMounted(() => {
  getBannerData()
  getBlogListData({ isOfficialRecommend: 1 })
  getRecommendUser()
  getAdminUser()
  getHomeBlogData()
})
</script>

<style scoped lang="scss">
@import '@/assets/style/reset.scss';
@import './index.scss';
</style>
